var trees = new Array();
var currentNode = null;
var zTreeObj ;
var operation = "update";
$(function() {
	var setting = {
			check : {
				enable : false
			},
			async : {
				enable : true,
				url : "admin/treenode/tree-node!listall",
				autoParam : [ "id=bean.id" ],
				otherParam : {}
			},
			callback : {
				onClick : zTreeOnClick,
				onAsyncSuccess:zTreeOnAsyncSuccess
			}
		};
		var root = {
			name : "系统全部权限",
			open : true,
			nocheck : false,
			id : "root",
			isParent : true
		};
		var zNodes = [ root ];
		zTreeObj = $.fn.zTree.init($("#resTree"), setting, zNodes);
		var nodes = zTreeObj.getNodes();
		zTreeObj.expandNode(nodes[0],true,false,true,true);

	$("#toolbar button").bind("click", function() {
		switch ($(this).attr("id")) {
		case "save":
			saveApply();
			break;
		case "clear":
			clearForm();
			break;
		case "remove":
			deleteNode();
			break;
		default:
			;
		}

	});

});// end of document ready

function zTreeOnClick(event, treeId, treeNode) {
	
	$("#parentId").val(treeNode.id);
	$("#id").val(treeNode.id);
	$("#identifier").val(treeNode.href);
	$("#description").val(treeNode.name);
	if(treeNode.id!='root')
	$("#webappid").val(treeNode['attrs']['webappId']);
	$("#cataId").val(treeNode['attrs']['catalog']);
	var leaf = !treeNode.isParent;
	$("#beantype" + leaf).attr("checked", true);
	$("#bean"+treeNode.visiable).attr("checked", "checked");
	currentNode = treeNode;	
}

var treeObj = new Object();

function saveApply() {
	saveOrUpdateNode();

}
function clearForm() {
	$("input[type='radio']").attr("checked", false);
	$("input[type='text']").val("");
	// $("#parentId").val($("#id").val());
	operation = "add";
	$("#id").val("");
}
function deleteNode() {
	var isSure = confirm("您确认删除此菜单吗,这将导致其子菜单都被删除!");
	if (!isSure)
		return;
	var postData = 'bean.id=' + $("#id").val();
	doSubmit("admin/treenode/tree-node!remove",postData,function(){
		if(currentNode.isParent){
	    	   zTreeObj.reAsyncChildNodes(currentNode, "refresh");

	    }
	});
}

function saveOrUpdateNode() {
	var postUrl = "admin/treenode/tree-node!"+operation;
	if ($("#parentId").val() == '' || $("#identifier").val() == ''
			|| $("#description").val() == '') {
		createNotify("父节点，URL，名称都必须有!");
		return;
	}
	
    doSubmit(postUrl,$("form").serialize(),function(){
    	var pNode;
    	if(currentNode.isParent){
    	   if(currentNode.children.length>0)
    	   zTreeObj.reAsyncChildNodes(currentNode, "refresh");
    	     
       }
       pNode = currentNode.getParentNode();
       zTreeObj.reAsyncChildNodes(pNode, "refresh");       
    });
}

function zTreeOnAsyncSuccess(event, treeId, treeNode, msg){
	/*var nodes = treeNode.children;
	
	for(var i=0;i<nodes.length;i++){
		zTreeObj.expandNode(nodes[i],true,false,true,true);	
	}*/

}